package org.edu.modules.oa.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.entity.VeFileFilesEntity;
import org.edu.modules.oa.entity.VeOaDocumentEntity;
import org.edu.modules.oa.mapper.IVeFileFilesMapper;
import org.edu.modules.oa.mapper.VeOaDocumentMapper;
import org.edu.modules.oa.service.IVeOaPersonDocumentService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.VeOaDocumentVo;
import org.edu.modules.oa.vo.VeOaYinzhangVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags="知识文档-个人文件")
@RestController
@RequestMapping("/oa/VeOaPersonDocument")
@Slf4j
public class VeOaPersonDocumentController {
    @Autowired
    private RedisUtil redisUtil; // redis服务类
    @Resource
    private OSS ossClient;
    @Resource
    private IVeOaPersonDocumentService iVeOaPersonDocumentService;
    //下载用的
    @Resource
    private VeOaDocumentMapper veOaDocumentMapper;
    @Resource
    private IVeFileFilesMapper iVeFileFilesMapper;


    //新增文件
    @AutoLog(value = "知识文档--新增文件")
    @ApiOperation(value="增加文件", notes="个人文件-增加文件")
    @PostMapping(value = "/addFile")
    public Result<?> addFile(MultipartFile file, VeOaDocumentEntity veOaDocumentEntity) throws Exception{
        System.out.println(veOaDocumentEntity);
        //判断所在的上级的可添加人员权限
        Integer checkResult = iVeOaPersonDocumentService.checkAddDocDirPower(veOaDocumentEntity);
        if (checkResult != 1){
            return Result.error(500,"无在当前文件夹下新建文件夹权限");
        }

        //创建文件类
        VeFileFilesEntity veFileFilesEntity = null;
        String fileName = null;
        String suffixName = null;
        if(file != null){
            //myFile为MultipartFile类型
//            CommonsMultipartFile cf= (CommonsMultipartFile)file;
//            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//            File document = fi.getStoreLocation();
            //把MultipartFile文件流转换成文件
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            System.out.println("文件名"+fileName);
            veOaDocumentEntity.setDocName(fileName);
            //同级下重复校验
            VeOaDocumentEntity chongfuDocEntity = iVeOaPersonDocumentService.checkNameByPid(veOaDocumentEntity);
            if (chongfuDocEntity != null){
                return Result.error(500,"当前路径下文件名重复");
            }

            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length-1];

            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                if (filename[0].length()>=3){
                    document=File.createTempFile(filename[0], filename[1]);
                }else {
                    document=File.createTempFile(filename[0]+"(1)", filename[1]);
                }

                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString();
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
            PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+fileName,document);
            //文件下载地址
            String path = "https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName;
            System.out.println("-----------文件下载地址-------"+path);
            veFileFilesEntity = new VeFileFilesEntity();
            //当前插入的时间
            Long time = System.currentTimeMillis()/1000;
            veFileFilesEntity.setSourceFile(path);
            veFileFilesEntity.setName("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
            veFileFilesEntity.setExt(suffixName);
            veFileFilesEntity.setCreateTime(time);
            veFileFilesEntity.setSize(size);
        }
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaDocumentEntity.setIsShare(0);
        veOaDocumentEntity.setIdType(1);
        veOaDocumentEntity.setIsDeleted(0);
        veOaDocumentEntity.setTerminalId(1);
        veOaDocumentEntity.setCreateUserId(user.getId());
        veOaDocumentEntity.setCreateUserName(user.getRealname());
        //添加文件
        Integer res = iVeOaPersonDocumentService.addDocFile(veOaDocumentEntity,veFileFilesEntity);
        if (res == 0){
            return Result.error(500,"添加文件失败");
        }

        return Result.OK();
    }

    //新建文件夹
    @AutoLog(value = "知识文档--新建文件夹")
    @ApiOperation(value="新建文件夹", notes="个人文件-新建文件夹")
    @PostMapping(value = "/addDir")
    public Result<?> addDir(VeOaDocumentEntity veOaDocumentEntity){
        System.out.println(veOaDocumentEntity);
        //同级下重复校验
        VeOaDocumentEntity chongfuDocEntity = iVeOaPersonDocumentService.checkNameByPid(veOaDocumentEntity);
        if (chongfuDocEntity != null){
            return Result.error(500,"当前路径下文件夹名重复");
        }
        //判断所在的上级的可添加人员权限
        Integer checkResult = iVeOaPersonDocumentService.checkAddDocDirPower(veOaDocumentEntity);
        if (checkResult != 1){
            return Result.error(500,"无在当前文件夹下新建文件夹权限");
        }

        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaDocumentEntity.setIsShare(0);
        veOaDocumentEntity.setIdType(0);
        veOaDocumentEntity.setIsDeleted(0);
        //veOaDocumentEntity.setDocType("个人");
        veOaDocumentEntity.setTerminalId(1);
        veOaDocumentEntity.setCreateUserId(user.getId());
        veOaDocumentEntity.setCreateUserName(user.getRealname());
        //新建文件夹
        Integer res = iVeOaPersonDocumentService.addDocDir(veOaDocumentEntity);
        if (res == 0){
            return Result.error(500,"新建文件夹失败");
        }

        return Result.OK();
    }

    //条件查询 进入下一级
    @AutoLog(value = "知识文档--进入下一级")
    @ApiOperation(value="条件查询", notes="个人文件-条件查询")
    @PostMapping(value = "/searchTable")
    public Result<?> searchTable(VeOaDocumentEntity veOaDocumentEntity,Integer startPage,Integer pageSize,String uploadDate) throws ParseException {
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        if (uploadDate != null && !uploadDate.equals("")){
            Date dateTixing=formatter.parse(uploadDate.trim());
            veOaDocumentEntity.setCreateTime(dateTixing);
        }

        veOaDocumentEntity.setIsDeleted(0);
        //veOaDocumentEntity.setDocType("个人");
        HashMap<String,Object> map = iVeOaPersonDocumentService.selectDocument(veOaDocumentEntity,startPage,pageSize);
        return Result.OK(map);
    }

    //条件查询 返回上一级
    @AutoLog(value = "知识文档--返回上一级")
    @ApiOperation(value="返回上一级", notes="个人文件-返回上一级")
    @PostMapping(value = "/backToUplevel")
    public Result<?> backToUplevel(VeOaDocumentEntity veOaDocumentEntity,Integer startPage,Integer pageSize,String uploadDate) throws ParseException {
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        if (uploadDate != null && !uploadDate.equals("")){
            Date dateTixing=formatter.parse(uploadDate.trim());
            veOaDocumentEntity.setCreateTime(dateTixing);
        }

        Integer isDelete = 0;
        String docType = veOaDocumentEntity.getDocType();
        HashMap<String,Object> map = iVeOaPersonDocumentService.backToUpLevel(veOaDocumentEntity,startPage,pageSize,isDelete,docType);
        if (map.size()<=0){
            return Result.error(500,"无上一级");
        }

        return Result.OK(map);
    }

    //查看详情
    @AutoLog(value = "知识文档--查看详情")
    @ApiOperation(value="查看详情", notes="个人文件-查看详情")
    @PostMapping(value = "/seeDetail")
    public Result<?> seeDetail(VeOaDocumentEntity veOaDocumentEntity){
        //拦截权限
        Integer checkResult = iVeOaPersonDocumentService.checkSeeDetailPower(veOaDocumentEntity.getId());
        if (checkResult != 1){
            return Result.error(500,"用户无权访问");
        }
        VeOaDocumentVo veOaDocumentVo = iVeOaPersonDocumentService.seeDocDetail(veOaDocumentEntity);
        return Result.OK(veOaDocumentVo);
    }

    //修改页面的查看详情
    @AutoLog(value = "知识文档--修改页面的查看详情")
    @ApiOperation(value="修改页面的查看详情", notes="个人文件-修改页面的查看详情")
    @PostMapping(value = "/seeDetailOfUpdate")
    public Result<?> seeDetailOfUpdate(VeOaDocumentEntity veOaDocumentEntity){
        VeOaDocumentVo veOaDocumentVo = iVeOaPersonDocumentService.seeDocDetail(veOaDocumentEntity);
        return Result.OK(veOaDocumentVo);
    }

    //修改文件/文件夹
    @AutoLog(value = "知识文档--修改文件/文件夹")
    @ApiOperation(value="修改文件/文件夹", notes="个人文件-修改文件/文件夹")
    @PostMapping(value = "/updateFileOrFolder")
    public Result<?> updateFileOrFolder(VeOaDocumentEntity veOaDocumentEntity){
        //查看权限
        Integer checkResult = iVeOaPersonDocumentService.checkUpdatePower(veOaDocumentEntity.getId());
        if (checkResult != 1){
            return Result.error(500,"用户无权修改");
        }
        //重复校验
        VeOaDocumentEntity chongfuDocEntity = iVeOaPersonDocumentService.checkNameByPid(veOaDocumentEntity);
        if (chongfuDocEntity != null){
            return Result.error(500,"修改的名称与同路径下的其它文件或文件夹重复");
        }

        VeFileFilesEntity veFileFilesEntity = new VeFileFilesEntity();
        Integer res = iVeOaPersonDocumentService.updateDocFileDir(veOaDocumentEntity,veFileFilesEntity);
        if (res == 0){
            return Result.error(500,"修改失败");
        }
        return Result.OK();
    }


    //导出表格
    @AutoLog(value = "知识文档--导出表格")
    @ApiOperation(value = "导出excel表格", notes = "个人文件-导出excel表格")
    @GetMapping(value = "/exportDocumentTable")
    //ModelAndView 导出表格流
    public ModelAndView exportDocumentTable(VeOaDocumentEntity veOaDocumentEntity,Integer startPage,Integer pageSize,String uploadDate) throws ParseException {
        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        if (uploadDate != null && !uploadDate.equals("")){
            Date dateTixing=formatter.parse(uploadDate.trim());
            veOaDocumentEntity.setCreateTime(dateTixing);
        }
        veOaDocumentEntity.setIsDeleted(0);
        //文件类型
        //veOaDocumentEntity.setDocType("个人");
        //获取登录人信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //查当前位置的数据
        List<VeOaDocumentVo> voList = iVeOaPersonDocumentService.export(veOaDocumentEntity,startPage,pageSize);
        //创建导出流
        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());
        //文件的文件名
        modelAndView.addObject(NormalExcelConstants.FILE_NAME,veOaDocumentEntity.getDocType()+"文件表");
        //数据的类型
        modelAndView.addObject(NormalExcelConstants.CLASS, VeOaDocumentVo.class);
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams(veOaDocumentEntity.getDocType()+"文件表","导出人:"+user.getRealname(),veOaDocumentEntity.getDocType()+"文件表");
        modelAndView.addObject(NormalExcelConstants.PARAMS,exportParams);
        modelAndView.addObject(NormalExcelConstants.DATA_LIST,voList);

        return modelAndView;

    }

    //删除选中
    @AutoLog(value = "知识文档--删除选中")
    @ApiOperation(value = "删除选中", notes = "个人文件-删除选中")
    @GetMapping(value = "/deleteAll")
    public Result<?> deleteAll(@RequestParam List<String> ids){
        System.out.println("删除的数组"+ids);
        List<Long> idList = new ArrayList<>();
        for (int i=0;i<ids.size();i++){
            System.out.println(ids.get(i));
            idList.add(Long.parseLong(ids.get(i)));
        }
        //判断选中的每个文件/文件夹的权限
        Boolean flag = true;
        Integer checkResult = 0;
        for (int i=0;i<idList.size();i++){
            checkResult = iVeOaPersonDocumentService.checkDeletePower(idList.get(i));
            if (checkResult != 1){
                flag = false;
                break;
            }
        }
        if (flag == false){
            return Result.error(500,"有一项或多项文件用户无权删除，请重新选择");
        }
        Integer res = 0;
        //Boolean flagDelete = true;
        for (int i=0;i<idList.size();i++){
            res = iVeOaPersonDocumentService.deleteDocument(idList.get(i));
        }
        if (res == 0){
            return Result.error(500,"删除过程中出现错误");
        }

        return Result.OK();
    }





}
